﻿(function ($) {
    var sourceGrid, mnggridid, contractpermistion, rowcommand, MaHD = 0, contractmngtemplate, _ct,
      Search = function () {
          $(mnggridid).data("kendoGrid").dataSource.read();
      },
      ViewDetail = function (e) {
          e.preventDefault();
          var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
          window.location.href = "/ContractDetail.aspx?MaHD=" + dataItem.MaHD;
      },
      ShowKCP = function (e) {
          var MaHD = 0;
          if (e != null) {
              e.preventDefault();
              var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
              MaHD = dataItem.MaHD;
              window.location.href = "/KCP.aspx?MaHD=" + dataItem.MaHD;
          }
      },
      AddKCP = function (e) {
          var vMaHD = 0;
          if (e != null) {
              e.preventDefault();
              var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
              vMaHD = dataItem.MaHD;
          }
         var  popupwindow = $("#kcpwindow");
          var wndwidth = $(window).width();
          popupwindow.kendoWindow({
              width: (wndwidth * 0.7) + "px",
              height: "600px",
              title: "Thêm/Sửa Khoán chi phí",
              content: "/KCPPopup.aspx?MaHD=" + vMaHD,
              modal: true,
              animation: false,
              center: true
          });
          popupwindow.data("kendoWindow").open().center();
      },
    DeleteHD = function (e) {
        e.preventDefault();
        var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        var mahddelete = dataItem.MaHD;
        if (confirm("Bạn có chắc chắn muốn xóa hợp đồng này không?")) {
            $.post("/Handlers/post.ashx", { MaHD: mahddelete, act: "xcontract" }, function (result) {
                if (result == "success") {
                    var grid = $(mnggridid).data('kendoGrid');
                    grid.dataSource.remove(dataItem);
                    showMessage('success', "Xóa hợp đồng thành công!");
                } else {
                    showMessage('error', "Không thể xóa hợp đồng này!");
                }
            });
        }
    },

    onDataBound = function (arg) {
        var _grid = this;
        _grid.tbody.find('>tr').each(function () {
            var dataItem = _grid.dataItem(this);
            if (dataItem.ParentID == "") {
                $(this).addClass('ct-root');
            } else {
                $(this).addClass('ct-child');
            }
        });
    };

    $.extend($.fn, {
        InitialContractGrid: function (options) {
            var o = $.extend({
            }, options);
            mnggridid = this;
            contractpermistion = o.contractpermistion;
            MaHD = o.ParentID;
            contractmngtemplate = o.contractmngtemplate;
            var contracttype = o.contracttype;
            var loadtype = o.loadtype;
            //permisstion
            rowcommand = new Array();
            if (contractpermistion >= 7) {
                rowcommand.push({ name: "Delete", text: "Xóa", click: DeleteHD });
                rowcommand.push({ name: "Detail", text: "Chi tiết", click: ViewDetail });
                if (MaHD==0)
                    rowcommand.push({ name: "AddKCP", text: "Thêm KCP", click: AddKCP });
            }
            else {
                if (contractpermistion >= 1) {
                    //co quyen xem danh sach hop dong
                    rowcommand.push({ name: "Detail", text: "Chi tiết", click: ViewDetail });
                } else {
                    //ko co quyen xem
                    return;
                }
            }

            //end permisstion

            sourceGrid = {
                serverPaging: true,
                batch: true,
                pageSize: 20,
                schema: {
                    data: function (data) {
                        if (data.d != null)
                            return data.d.source;
                        else
                            return data.d;
                    },
                    total: function (data) {
                        if (data.d != null)
                            return data.d.total;
                        else
                            return data.d;
                    },
                    model: {
                        id: "MaHD",
                        fields: {
                            STT: { editable: false, nullable: true },
                            TenHD: { validation: { required: true} },
                            SoHD: { validation: { required: false} },
                            DepartmentID: { validation: { required: false} },
                            MaDoiTac: { validation: { required: false} },
                            GiaTriHD: { type: "number", validation: { required: false} },
                            GiaTriThanhLyHD: { type: "number", validation: { required: false} },
                            CanhBaoTruoc: { type: "number", validation: { required: false, min: 1} }
                        }
                    }
                },
                transport: {
                    read: {
                        url: "/WS/hdservice.aspx/GetListContract",
                        contentType: "application/json; charset=utf-8",
                        type: "POST"
                    },
                    update: {
                        url: "/WS/hdservice.aspx/UpdateContract",
                        contentType: "application/json; charset=utf-8",
                        type: "POST",
                        complete: function (e) {
                            showMessage('success', "Cập nhật thành công");
                            $(mnggridid).data("kendoGrid").dataSource.read();
                        },
                        error: function (e) {
                            alert('error');
                        }
                    },
                    destroy: {
                        url: "/WS/hdservice.aspx/DeleteContract",
                        contentType: "application/json; charset=utf-8",
                        type: "POST",
                        complete: function (e) {
                            var msg = e.responseText.toString();
                            if (msg.indexOf("failed") != -1) {
                                showMessage('error', "Không thể xóa hợp đồng này!");
                            }
                            else
                                showMessage('success', "Cập nhật thành công");
                            $(mnggridid).data("kendoGrid").dataSource.read(); //refresh grid
                        },
                        error: function (e) {
                            alert('error');
                        }
                    },
                    create: {
                        url: "/WS/hdservice.aspx/CreateContract",
                        contentType: "application/json; charset=utf-8",
                        type: "POST",
                        complete: function (e) {
                            showMessage('success', "Cập nhật thành công");
                            $(mnggridid).data("kendoGrid").dataSource.read();
                        },
                        error: function (e) {
                            alert('error');
                        }
                    },
                    parameterMap: function (data, operation) {
                        if (operation != "read") {
                            if (operation == "create") {
                                return JSON.stringify({ obj: data.models, ParentID: MaHD, ContractType: contracttype })
                            }
                            return JSON.stringify({ obj: data.models })
                        }
                        else {
                            var keyword = $("#txtAdress").val();
                            var SoHD = $("#txtSoHD").val();
                            var DoiTac = $("#txtDoitac").val();
                            var FromDT = $("#txtfromdate").val();
                            var ToDT = $("#txttodate").val();
                            var phongid = $("#drphong").val();
                            data = $.extend({ Keyword: keyword, SoHD: SoHD, DoiTac: DoiTac, FromDT: FromDT, ToDT: ToDT, ParentID: MaHD, ContractType: contracttype, LoadType: loadtype, DepartmentID: phongid }, data);
                            return JSON.stringify({ obj: data });
                        }
                    }
                }
            };

            var grid = $(mnggridid).kendoGrid({
                dataSource: sourceGrid,
                toolbar: kendo.template($(contractmngtemplate).html()),
                pageable: true,
                resizable: true,
                navigatable: true,
                
                dataBound: onDataBound,
                columns: [
                                {
                                    field: "STT", title: "STT", width: "55px", editable: false, nullable: true
                                },
                                {
                                    field: "TenHD", title: "Tên hợp đồng", width: "250px", editor: textEditorInitialize
                                },
                                {
                                    field: "SoHD", title: "Số", width: "120px"
                                },
                                {
                                    field: "DepartmentID",
                                    title: "Phòng",
                                    width: "150px",
                                    template: "${getDepartmentsName(DepartmentID)}",
                                    editor: gridDropDownEditor
                                },
                                 {
                                     field: "TenDoiTac", title: "Đối tác", width: "150px", editor: textAutocompleteInitialize
                                 },
                                 {
                                     field: "NgayTaoHD", title: "Ngày", type: "date",width:"100px", format: "{0:dd/MM/yyyy}", editor: columndatepicker
                                 },
                                {
                                    field: "GiaTriHD", title: "Giá trị", format: "{0:N}",width:"150px"
                                },
                                {
                                    field: "ThoiGianNopBaoCao", title: "Thời gian nộp báo cáo",width:"100px", type: "date", format: "{0:dd/MM/yyyy}", editor: columndatepicker
                                },
                                {
                                    field: "CanhBaoTruoc", title: "Cảnh báo trước",width:"60px"
                                },
                                {
                                    field: "TienDoThucHien", title: "Tiến độ thực hiện",width:"130px"
                                },
                                {
                                    field: "GhiChu", title: "Ghi chú",editor: textEditorInitialize,width:"130px"
                                },
                                {
                                    field: "ChuNhiemCongTrinh", title: "CN Công trình",width:"100px"
                                },
                                {
                                    field: "NgayThanhLyHD", title: "Ngày TLHĐ", type: "date", format: "{0:dd/MM/yyyy}", editor: columndatepicker,width:"120px"
                                },
                                {
                                    field: "GiaTriThanhLyHD", title: "Giá trị TLHĐ", format: "{0:N}",width:"120px"
                                },
                                { command: rowcommand,
                                    title: " ",
                                    width: "100px"//(rowcommand.length == 1 ? "90px" : (rowcommand.length * 65) + "px")
                                }
                            ],
                editable: (contractpermistion >= 7)
            });
            $(".k-search-button").click(function () { Search(); });
            $("#txtAdress,#txtSoHD").bind("keydown", function (event) {
                var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
                if (keycode == 13) {
                    Search();
                    return false;
                } else {
                    return true;
                }
            });
        }
    });
} (jQuery));